package com.adouteam.simple.wechat.service;

import com.adouteam.simple.wechat.base.WechatConstants;
import com.adouteam.simple.wechat.base.WeixinUrls;
import com.adouteam.simple.wechat.bean.media.MediaForm;
import com.adouteam.simple.wechat.bean.media.MediaResult;
import com.adouteam.simple.wechat.bean.media.MediaType;
import com.adouteam.simple.wechat.tool.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * 多媒体资源服务
 *
 * @author buxianglong
 */
public class MediaService{
    public static final Logger logger = LoggerFactory.getLogger(MediaService.class);

    public static MediaResult uploadTempMedia(MediaForm mediaForm, WechatConstants wechatConstants){
        if(null == mediaForm || null == mediaForm.getType() || null == mediaForm.getMedia()){
            return null;
        }
        String url = WeixinUrls.replace(WeixinUrls.MEDIA_TEMP_UPLOAD_URL, wechatConstants, new HashMap<String, String>(){{
            put("TYPE", mediaForm.getType().getValue());
        }});
        HttpEntity httpEntity = MultipartEntityBuilder.create()
                .addBinaryBody("media", mediaForm.getMedia())
                .build();
        return HttpUtil.post(url, null, httpEntity, (httpResponse -> {
            String responseContent = EntityUtils.toString(httpResponse.getEntity(), Charset.forName("UTF-8"));
            if(StringUtils.isBlank(responseContent)){
                return null;
            }
            return JSONObject.parseObject(responseContent, MediaResult.class);
        }));
    }

    public static InputStream getTempMedia(MediaType mediaType, String mediaId, WechatConstants wechatConstants){
        Map<String, String> map = new HashMap<>(1);
        map.put("MEDIA_ID", mediaId);
        String url = WeixinUrls.replace(
                mediaType == MediaType.VIDEO ? WeixinUrls.MEDIA_TEMP_GET_URL_OF_HTTP : WeixinUrls.MEDIA_TEMP_GET_URL,
                wechatConstants, map);
        return HttpUtil.get(url, null, (httpResponse) -> new BufferedHttpEntity(httpResponse.getEntity()).getContent());
    }
}
